<template>
  <div class="wrapper-page">
    <div class="left-wratter">
      <img src="@/assets/images/login/100buy_login.png" class="login-img" alt="" />
    </div>
    <div class="right-wrapper">
      <div class="right-content" v-if="signStatus">
        <!-- <img src="@/assets/images/home/logo.png" class="logo-img" @click="jumpMet()" alt="" /> undone-->
        <div class="title-text">{{ $t("public.register") }}</div>
        <!-- 选择国家暂时去掉 -->
        <!-- <Select filterable :placeholder="$t('register.selectCountry')" @on-change="onSelect" class="select"
              size="large" v-model="form.countryCode">
              <Avatar v-if="currentCountryInfo.flagImg" :src="currentCountryInfo.flagImg" slot="prefix" size="small" />
              <Option v-for="item in countryList" :label="item.text" :value="item.code" :key="item.code">
                <div class="country-item">
                  <img class="country-logo" :src="item.flagImg" alt="" />
                  <span>{{ item.text }}</span>
                </div>
              </Option>
            </Select> -->
        <!-- <div class="div-input">
              <Input size="large" v-model="form.username" @input="TypeInput($event)"
                :placeholder="$t('register.enterUserName') + $t('register.alphanumeric')" />
            </div> -->
        <div class="div-input">
          <Input size="large" v-model="form.email" @on-change="validateEmail" :placeholder="$t('public.enterEmail')" />
          <div v-if="!isValidEmail" style="color: red">
            {{ $t("login.validEmail") }}
          </div>
        </div>
        <div class="div-input">
          <Input size="large" v-model="form.password" :placeholder="$t('public.enterPassword')" password
            type="password" />
        </div>
        <div class="div-input">
          <Input size="large" v-model="form.cPassword" :placeholder="$t('public.confirmPassword')" password
            type="password" />
        </div>
        <div class="div-input">
          <Input size="large" v-model="form.inviteCode" :placeholder="$t('register.invitationCode')" />
        </div>
        <div class="agreement">
          <Checkbox v-model="single">
            <i18n path="register.consentAgreement">
              <span class="text" slot="registerAgreement" @click="jump()">{{
                $t("register.userRegistrationProtocol")
              }}</span>
              <!-- <router-link :to="`/notice/${userAgreement.id}`" target="_blank" slot="registerAgreement"
                    class="text">{{ $t("register.userRegistrationProtocol") }}</router-link> -->
              <router-link :to="`/notice/${privateAgreement.id}`" slot="privacyAgreement" target="_blank"
                class="text">{{ $t("register.privacyStatement") }}</router-link>
            </i18n>
          </Checkbox>
        </div>
        <Button class="btn" :loading="loading" @click="onRegister" type="primary" size="large">
          {{ $t("public.register") }}
        </Button>
        <div class="fun">
          {{ $t("public.alreadyHaveAccount")
          }}<router-link class="fun-item" to="/login">
            {{ $t("public.login") }}
          </router-link>
        </div>
        <Divider>
          <div class="other-text">{{ $t("public.otherLoginChannel") }}</div>
        </Divider>
        <div class="login-way">
          <!-- <div class="way">
              <img src="@/assets/images/login/apple.png" alt="">
            </div> -->
          <div class="way" @click="loginWithGoogle">
            <img src="@/assets/images/login/google.png" alt="" />
          </div>
        </div>
      </div>
      <div class="right-content" v-else>
        <!-- <img src="@/assets/images/home/logo.png" class="logo-img" @click="jumpMet()" alt="" /> undone-->
        <div class="code-text">{{ $t("register.validate_title") }}</div>
        <div class="code-desc">
          {{ $t("register.validate_tips_before") }}{{ form.email }}，{{
            $t("register.validate_tips_after")
          }}
        </div>
        <div class="verification-code-input">
          <Input v-for="(item, index) in codeLength" :key="index" class="code-input-item" maxlength="1"
            @input="(event) => handleInput(event, index)" ref="codeInput" />
        </div>
        <div class="resend-tips" v-if="!isHide">
          {{ $t("register.again_send") }}（{{ num }}S）
        </div>
        <div class="resend-tips" style="color: #333333;cursor: pointer;" v-if="isHide" @click="onRegister">
          {{ $t("register.again_send") }}
        </div>
        <div class="revise-text" @click="changeBtn">
          {{ $t("register.edit_email") }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { GoogleOAuthProvider } from "google-oauth-gsi";

const googleProvider = new GoogleOAuthProvider({
  clientId:
    "742076253847-gtutc8pr8n85t27hju53m7srmjjdumgu.apps.googleusercontent.com",
  onScriptLoadError: () => console.log("onScriptLoadError"),
  onScriptLoadSuccess: () => console.log("onScriptLoadSuccess"),
});
import {
  register,
  sendCodeByEmail,
  getRoute,
  getCallback,
  loginWithGoogleOauth2,
} from "@/api/user";
import { mapState } from "vuex";
import { contentTypeList } from "@/api/content";
import { pointUser } from "@/common/point/api-hook";//打点日志
import { debounce } from "@/common/common";
export default {
  name: "index",
  data() {
    return {
      oathCode: "",
      codeLength: 6, // 设置验证码的长度
      codeTime: 59,
      signStatus: true,
      appName: process.env.VUE_APP_NAME,
      codeLoading: false, // 发送验证码code
      currentCountryInfo: {
        flagImg: "",
        text: "",
        code: "",
      },
      num: 60,
      timer: "",
      loading: false,
      single: false, // 同意注册协议
      privacyInfo: "", // 隐私信息
      form: {
        countryCode: "US", // 国家编码
        currencyCode: "", // 币种编码
        email: "", // 邮箱
        emailCode: "", // 验证码
        password: "", // 登录密码
        cPassword: "", // 确定登录密码
        username: "", // 用户名
        inviteCode: "",
        activityCode: ""
      },
      isValidEmail: true,
      defaultForm: {
        countryCode: "US",
      },
      isHide: false
    };
  },
  computed: {
    ...mapState({
      countryList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.countryList;
        }
        return list;
      },
      userAgreement: (state) => {
        // 用户协议
        let obj = "";
        if (state.config.config) {
          obj = state.config.config.articleMap.CFG_ARTICLE_REGISTER;
        }
        return obj;
      },
      privateAgreement: (state) => {
        // 隐私协议
        let obj = "";
        if (state.config.config) {
          obj = state.config.config.articleMap.CFG_ARTICLE_PRIVATE;
        }
        return obj;
      },
      userLanguage: (state) => state.user.userLanguage,
      userCurrency: (state) => state.user.userCurrency,
    }),
  },
  created() {
    let code = sessionStorage.getItem("INVITE_CODE");
    if (code) {
      this.form.inviteCode = code;
    }
    if (this.$route.query.activityCode) {
      this.form.activityCode = this.$route.query.activityCode;
    }

    let activityCode = sessionStorage.getItem("ACTIVITY_CODE");
    if (activityCode) {
      this.form.activityCode = activityCode;
    }

    const pathUrl = localStorage.getItem("prevPage");
    if (pathUrl) {
      const checkWords = ["login", "register", "forgot"];
      for (const word of checkWords) {
        if (pathUrl.includes(word)) {
          localStorage.removeItem("prevPage");
          break; // 如果找到匹配的，执行删除操作后就可以跳出循环了，因为目的已经达到
        }
      }
    }
    // this.getContentTypeList();
  },
  methods: {
    jumpMet() {
      this.$router.push('/')
    },
    loginWithGoogle() {
      const googleLoginConnector = googleProvider.useGoogleLogin({
        flow: "implicit",
        onSuccess: (res) => this.handleCredentialResponse(res),
        onError: (err) => console.error("Failed to login with google", err),
      });
      googleLoginConnector();
    },
    handleInput(event, index) {
      let inputValue = event;
      if (inputValue) {
        // 如果是正常输入
        if (this.oathCode.length === index) {
          if (
            this.oathCode.length < this.codeLength &&
            index + 1 < this.$refs.codeInput.length
          ) {
            this.$refs.codeInput[index + 1].focus();
          }
          this.oathCode += inputValue;
        } else {
          if (
            this.oathCode.length < this.codeLength &&
            index + 1 < this.$refs.codeInput.length
          ) {
            this.$refs.codeInput[index + 1].focus();
          }
          // 如果是修改操作
          this.oathCode =
            this.oathCode.slice(0, index) +
            inputValue +
            this.oathCode.slice(index + 1);
        }
      } else {
        // 如果是删除操作
        if (this.oathCode.length > index && index > 0) {
          this.oathCode =
            this.oathCode.slice(0, index) + this.oathCode.slice(index + 1);
          this.$nextTick(() => {
            if (this.$refs.codeInput[index - 1]) {
              this.$refs.codeInput[index - 1].focus();
            }
          });
        }
      }
      this.form.currencyCode = this.userCurrency.code;
      this.form.emailCode = this.oathCode;
      if (this.oathCode.length === this.codeLength) {
        // 用户注册埋点
        if (this.$analytics) {
          this.$analytics.logEvent("register", { register_type: "email" });
        }

        // event的值
        let event = sessionStorage.getItem("eventValue");
        if (event) {
          this.form.utmParam = event;
        }

        this.form.username = this.form.email;
        this.loading = true;
        const { inviteCode } = this.$route.query;
        this.form.countryCode = this.form.countryCode.trim();
        this.form.email = this.form.email.trim();
        this.form.emailCode = this.form.emailCode.trim();
        this.form.password = this.form.password.trim();
        this.form.cPassword = this.form.cPassword.trim();
        this.form.username = this.form.username.trim();
        this.form.inviteCode = this.form.inviteCode.trim();
        this.form.activityCode = this.form.activityCode.trim();
        register({
          ...this.form,
          inviteCode: this.form.inviteCode || inviteCode,
        })
          .then((res) => {
            localStorage.setItem("USER_TOKEN", res.result.xaccessToken);
            this.$store.commit("setUserToken", res.result.xaccessToken);
            this.$Message.success(this.$t("login.loginSuccess"));
            this.$store.dispatch("getUserInfo");

            pointUser('register');

            // 注册登录之后回到之前查看的页面
            const prevPage = localStorage.getItem("prevPage");
            localStorage.removeItem("prevPage");
            if (prevPage) {
              window.location.href = prevPage;
            } else if (this.$route.query.redirection) {
              this.$router.push(this.$route.query.redirection);
            } else {
              this.$router.push("/");
            }

            if (window.ssq) {
              ssq.push("clearUser");
              ssq.push("setLoginInfo", {
                user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
                user_name: res.result.userInfo.userName, // 对应用户名
                language: "en-US", // 对应用户语言
                email: res.result.userInfo.email,
              });
            }
            // this.$Message.success(this.$t("register.registeredSuccess"));
            // this.$router.push("/login");
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    changeBtn() {
      this.signStatus = true;
    },
    async handleCredentialResponse(response) {
      // event的值
      let event = sessionStorage.getItem("eventValue");
      if (event) {
        this.defaultForm.utmParam = event;
      }
      (this.defaultForm.source = "google"),
        (this.defaultForm.currencyCode = this.userCurrency.code);
      this.defaultForm.lang = this.userLanguage.code;
      this.defaultForm.inviteCode = sessionStorage.getItem("INVITE_CODE");
      this.defaultForm.activityCode = this.form.activityCode;
      this.defaultForm.code = response.access_token;
      loginWithGoogleOauth2(this.defaultForm).then((res) => {
        this.loading = false;
        localStorage.setItem("USER_TOKEN", res.result.xaccessToken);
        this.$store.commit("setUserToken", res.result.xaccessToken);
        this.$Message.success(this.$t("login.loginSuccess"));
        this.$store.dispatch("getUserInfo");

        pointUser('register');

        if (this.$route.query.redirection) {
          this.$router.push(this.$route.query.redirection);
        } else {
          this.$router.push("/");
        }
        if (window.ssq) {
          ssq.push("clearUser");
          ssq.push("setLoginInfo", {
            user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
            user_name: res.result.userInfo.userName, // 对应用户名
            language: "en-US", // 对应用户语言
            email: res.result.userInfo.email,
          });
        }
      });
    },
    jump() {
      this.$router.push(`/notice/${this.userAgreement.id}`);
    },
    eachMeth(val) {
      let urlParams = new URLSearchParams(val.split("?")[1]);
      let stateValue = urlParams.get("state");
      let codeValue = urlParams.get("code");
      let sourceValue = urlParams.get("source");
      if (!sourceValue) {
        sourceValue = "google";
      }
      if (
        urlParams.has("state") &&
        stateValue !== null &&
        stateValue !== "" &&
        urlParams.has("code") &&
        codeValue !== null &&
        codeValue !== ""
      ) {
        getCallback(sourceValue, val).then((res) => {
          localStorage.setItem("USER_TOKEN", res.result.xaccessToken);
          this.$store.commit("setUserToken", res.result.xaccessToken);
          this.$Message.success(this.$t("login.loginSuccess"));
          this.$store.dispatch("getUserInfo");

          pointUser('register');

          // 登录之后回到之前查看的页面
          const prevPage = localStorage.getItem("prevPage");
          localStorage.removeItem("prevPage");
          if (prevPage) {
            window.location.href = prevPage;
          } else if (this.$route.query.redirection) {
            this.$router.push(this.$route.query.redirection);
          } else {
            this.$router.push("/");
          }
          if (window.ssq) {
            ssq.push("clearUser");
            ssq.push("setLoginInfo", {
              user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
              user_name: res.result.userInfo.userName, // 对应用户名
              language: "en-US", // 对应用户语言
              email: res.result.userInfo.email,
            });
          }
        });
      }
    },
    // 谷歌登录
    googleBtn() {
      (this.defaultForm.source = "google"),
        (this.defaultForm.currencyCode = this.userCurrency.code);
      this.defaultForm.lang = this.userLanguage.code;
      this.defaultForm.inviteCode = sessionStorage.getItem("INVITE_CODE");
      this.defaultForm.activityCode = this.form.activityCode;
      getRoute(this.defaultForm).then((res) => {
        window.location.href = res.result;
      });
    },
    getContentTypeList() {
      // 隐私协议
      contentTypeList({
        position: "privacy",
        pid: "0",
      }).then((res) => {
        this.privacyInfo = res.result.length > 0 ? res.result[0] : "";
      });
      // contentTypeList({
      //   position: 'privacy',
      //   pid: '0'
      // }).then((res)=>{
      //   this.privacyInfo = res.result.length > 0 ? res.result[0] : '';
      // })
    },
    onSelect(value) {
      let info = this.countryList.find((item) => {
        return item.code == value;
      });
      this.currentCountryInfo = { ...this.currentCountryInfo, ...info };
    },
    onRegister() {
      if (!this.form.countryCode) {
        this.$Message.error(this.$t("register.selectCountry"));
        return;
      }
      // if (!this.form.username) {
      //   this.$Message.error(this.$t("register.enterUserName"));
      //   return;
      // }
      if (!this.form.email) {
        this.$Message.error(this.$t("login.enterEmailAccount"));
        return;
      }
      // if (!this.validateEmail(this.form.email)) {
      //   this.$Message.error(this.$t("login.validEmail"));
      //   return;
      // }
      if (!this.form.password) {
        this.$Message.error(this.$t("public.enterPassword"));
        return;
      }
      if (!this.form.cPassword) {
        this.$Message.error(this.$t("public.confirmPassword"));
        return;
      }
      if (this.form.password != this.form.cPassword) {
        this.$Message.error(this.$t("public.passwordsMatch"));
        return;
      }
      if (!this.single) {
        this.$Message.error(
          this.$t("register.registrationAgreementAndPrivacyStatement")
        );
        return;
      }
      // 发送验证码
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = "";
      }
      this.codeLoading = true;
      sendCodeByEmail({
        email: this.form.email,
        type: 0,
      })
        .then((res) => {
          if (res.code == 200) {
            this.signStatus = false;
            this.codeLoading = false;
            this.$Message["info"]({
              content: res.message,
            });
            this.countdown();
          }
        })
        .catch(() => {
          this.codeLoading = false;
        });
    },
    sendCode() {
      // 发送验证码
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = "";
      }
      this.codeLoading = true;
      sendCodeByEmail({
        email: this.form.email,
        type: 0,
      })
        .then((res) => {
          this.codeLoading = false;
          this.countdown();
        })
        .catch(() => {
          this.codeLoading = false;
        });
    },
    countdown() {
      // 倒计时
      this.timer = setInterval(() => {
        if (this.num <= 0) {
          clearInterval(this.timer);
          this.timer = "";
          this.num = 60;
          this.isHide = true;
        } else {
          this.isHide = false;
          this.num = this.num - 1;
        }
      }, 1000);
    },
    TypeInput(e, val) {
      // 只能输入数字、字母、.、-、_ 的验证
      const inputType = /[^\w.\-_]/g; // 匹配除了字母、数字、.、-、_ 之外的任何字符

      // 进行替换和赋值操作
      this.$nextTick(() => {
        // 在赋值之前进行判断和替换
        if (e.match(inputType)) {
          // 匹配到不允许的字符，进行替换操作
          this.form.username = e.replace(inputType, "");
        } else {
          // 没有匹配到不允许的字符，直接赋值
          this.form.username = e;
        }
      });
    },
    validateEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      this.isValidEmail = emailRegex.test(this.form.email);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ivu-input {
  height: 68px;
  border-radius: 8px 8px 8px 8px;
  border: 1px solid #dddfe6;
  padding: 20px;
  font-size: 20px;
}

.wrapper-page {
  width: 100%;
  height: 100%;
  min-height: 1080px;
  background-color: #ff72a4;
  display: flex;
  align-items: center;

  .left-wratter {
    width: 50%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .login-img {
      width: 636px;
      height: 728px;
    }
  }

  .right-wrapper {
    width: 50%;
    height: 100%;
    min-height: 1080px;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 90px 0;

    .right-content {
      margin: 0 190px;
      text-align: center;

      .logo-img {
        width: 275px;
        height: 65px;
        margin-bottom: 28px;
        cursor: pointer;
      }

      .title-text {
        font-size: 32px;
        color: #222222;
        font-weight: 500;
        text-align: left;
      }

      .div-input {
        margin: 20px 0;
        text-align: left;

        .label {
          margin-bottom: 8px;
          color: @t-title-color;
          font-size: 16px;
          font-weight: 500;
        }

        .code-wrap {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .code {
            width: 102px;
            height: 44px;
            margin-left: 16px;
            background: #ffffff;
            border-radius: 4px 4px 4px 4px;
            opacity: 1;
            overflow: hidden;
            cursor: pointer;
            border: 1px solid @t-table-border-color;

            img {
              display: block;
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .agreement {
        text-align: left;

        .ivu-checkbox-wrapper {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 22px;
          color: #a2a2a2;
          line-height: 25px;
        }
      }

      .btn {
        width: 100%;
        background: #ff186b;
        border-color: #ff186b;
        height: 68px;
        font-size: 26px;
        border-radius: 10px;
        margin-top: 26px;
      }

      .fun {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 16px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 23px;
        color: #222222;
        line-height: 27px;

        &-item {
          color: #ff186b;
          font-size: 23px;

          &:hover {
            color: @primary-color;
          }
        }

        .text-tips {
          color: #ff186b;
        }
      }

      .other-text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 18px;
        color: #cdcdcd;
        line-height: 21px;
        margin: 20px 0;
      }

      .login-way {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 14px;

        .way {
          margin: 0 56px;
          cursor: pointer;

          img {
            display: block;
            width: 32px;
          }
        }
      }

      .code-text {
        font-weight: bold;
        font-size: 35px;
        color: #222222;
        line-height: 41px;
        text-align: left;
      }

      .code-desc {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 21px;
        color: #a2a2a2;
        line-height: 24px;
        margin-top: 24px;
        text-align: left;
      }

      .error-tips {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 21px;
        color: #f12e3f;
        line-height: 25px;
        text-align: left;
        margin-top: 14px;
      }

      .resend-tips {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 21px;
        color: #a2a2a2;
        line-height: 25px;
        text-align: left;
        margin-top: 10px;
      }

      .revise-text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 21px;
        color: #a2a2a2;
        line-height: 25px;
        text-align: left;
        margin-top: 30px;
        cursor: pointer;
      }

      .verification-code-input {
        display: flex;
        justify-content: space-between;
        margin-top: 34px;

        /deep/.ivu-input {
          width: 74px;
          height: 74px;
          font-size: 32px;
          font-weight: bold;
          padding: 27px;
        }

        .code-input-item {
          max-width: 100%;
          margin: 0;
          padding: 0;
          text-align: center;
        }
      }
    }
  }
}
</style>
